<template>
    <div style=" position: relative;"><el-card>
            <template #header>
                <!-- 搜索 -->
                <div>
                    <el-input style="width: 260px;" v-model="find_data.find" placeholder="客户名称,手机号或单位名称关键字" clearable
                        prefix-icon="Search" />
                    <!-- <el-date-picker style="width: 350px;margin-left:20px;" v-model="data_time" @change="datetime_btn"
                        type="datetimerange" start-placeholder="开始时间" end-placeholder="结束时间" format="YYYY-MM-DD HH:mm:ss"
                        value-format="YYYY-MM-DD HH:mm:ss" /> -->
                    <el-button style="margin-left: 20px;height:30px" @click="search_btn" type="primary"
                        icon="Search">搜索</el-button>
                </div>
                <!-- 功能按钮 -->
                <!-- <div style="margin-top:10px;display: flex;">
                    <el-button @click="add_btn" type="primary" icon="SuccessFilled">添加</el-button>
                    <el-button @click="up_btn" type="warning" icon="WarnTriangleFilled">修改</el-button>
                    <el-button @click="del_btn" type="danger" icon="CircleCloseFilled">删除</el-button>
                </div> -->
            </template>
            <div>
                <el-table border @selection-change="selection_change_btn" height="67vh" ref="multipleTableRef"
                    :data="list_data" style="width: 100%">
                    <el-table-column type="selection" width="35" />
                    <el-table-column label="编号" width="55" fixed type="index" />
                    <template v-for="item in table_data_list_new" :key="item.field">
                        <el-table-column v-if="item.off" :width="item.width" :prop="item.field" :label="item.label">
                            <template v-if="item.field == 'set'" #="{ row, column, $index }">
                                <el-button @click="set_btn(row)" type="primary" size="small">订单列表</el-button>

                            </template>
                        </el-table-column>
                    </template>


                </el-table>
            </div>

            <div style="margin-top:20px">
                <el-pagination @current-change="current_change_btn" @size-change="size_change_btn"
                    v-model:current-page="find_data.page.pageNum" v-model:page-size="find_data.page.pageSize"
                    :page-sizes="[20, 50, 100, 200]" :background="true"
                    layout="prev, pager, next, jumper,->,sizes,total," :total="total" />
            </div>
        </el-card>
    </div>

    <!-- 弹窗 -->
    <div>
        <!-- 表格筛选 -->
        <div style="position: absolute;top:60px;z-index: 9999;" :style="icon_off ? 'right:0px;' : 'right:110px;'">
            <el-icon @click="icon_btn" :size="20">
                <Setting />
            </el-icon>
            <div v-show="icon_off"
                style=" position: relative;top:-100px;right:140px;width: 130px;height:430px;background:#fff;overflow: hidden;">
                <div class="cols-set" style="background:#fff;width:90%;height:97%;margin:auto;margin-top:10px;">
                    <div>
                        <el-button-group style="display: flex; ">
                            <el-tooltip effect="dark" placement="bottom">
                                <template #content>注意：拖动下面的项，可以改变表格列的顺序，<br />记得点击保存才会永久生效哦！ </template>
                                <el-button style="width:10px" type="primary" icon="WarningFilled"></el-button>
                            </el-tooltip>
                            <el-button title="重置" type="primary" icon="Refresh" @click="resetTableSet"></el-button>
                            <el-button title="保存" type="primary" icon="Check" @click="saveTableSet"></el-button>
                        </el-button-group>
                        <div ref="sortableContainer" class="col-items" style="height:400px; overflow-y: auto; ">
                            <el-checkbox class="drag_it" @change="checkbox_btn" v-for="item in sortedItems"
                                :key="item.field" v-model="item.off" :label="item.label" border>
                            </el-checkbox>
                        </div>

                    </div>
                </div>
            </div>
        </div>
        <!-- 添加修改 -->
        <el-dialog style="margin-top:5vh" v-model="add_off" :title="title" width="40%" :close-on-click-modal='false'>
            <el-form :model="add_data" ref="formRef" label-width="130px" label-suffix="：">
                <el-form-item label="账户名称" prop="bankName" :rules="[
                    { required: true, message: '请输入账户名称', trigger: 'blur' },
                ]">
                    <el-input style="width: 400px;" maxlength="30" show-word-limit clearable v-model="add_data.bankName"
                        placeholder="请输入账户名称" />
                </el-form-item>
                <el-form-item prop="cardName" label="开户行" :rules="[
                    { required: true, message: '请输入开户行', trigger: 'blur' },
                ]">
                    <el-input maxlength="30" show-word-limit clearable style="width: 400px;" v-model="add_data.cardName"
                        placeholder="请输入开户行" />
                </el-form-item>
                <el-form-item label="账号" prop="cardNo" :rules="[{ required: true, message: '请输入账号', trigger: 'blur' }]">
                    <el-input maxlength="30" show-word-limit clearable style="width: 400px;" v-model="add_data.cardNo"
                        placeholder="请输入账户名称" />
                </el-form-item>
            </el-form>


            <el-button @click="ok_btn" style="margin-left:30vw" type="primary">确认提交</el-button>
        </el-dialog>

        <!-- 订单列表设置 -->
        <el-dialog style="margin-top:5vh" v-model="set_off" title="被推荐人订单列表" width="80%" :close-on-click-modal='false'>
            <div ref="dgtools" class="filter-container">
                <div class="dgts-row">
                    <div class="dgts-text-tj1">
                        <b style='font-weight:700;' class="tr-it-title">统计</b>
                        <el-divider direction="vertical"></el-divider>
                        <b style='font-weight:700;color:red' class="tr-it c-red">订单总价：{{ tj.totalPrice || 0 }}元</b>
                        <el-divider direction="vertical"></el-divider>
                        <b style='font-weight:700;color:green'>可提成总金额：{{ tj.agentPrice || 0 }}元</b>
                        <el-divider direction="vertical"></el-divider>
                        <b style='font-weight:700;color:red'>已提成总金额：{{ tj.alreadyAgentPrice || 0 }}元</b>
                    </div>


                </div>

                <div class="dgts-fm">
                    <el-form :model="ps_find" :inline="true">


                        <el-form-item prop="timeType">
                            <el-select v-model="ps_find.timeType" clearable filterable :placeholder="'时间类型'"
                                style="width: 120px">
                                <el-option label="用车时间" value="0">
                                </el-option>
                                <el-option label="下单时间" value="1">
                                </el-option>
                                <el-option label="续团时间" value="2">
                                </el-option>
                            </el-select>
                        </el-form-item>

                        <el-form-item prop="sedate">
                            <el-date-picker style="width: 350px;margin-left:20px;" v-model="data_time2"
                                @change="datetime_btn2" type="datetimerange" start-placeholder="开始时间"
                                end-placeholder="结束时间" format="YYYY-MM-DD HH:mm:ss"
                                value-format="YYYY-MM-DD HH:mm:ss" />
                        </el-form-item>



                        <!-- <el-form-item prop="plateNum">
                        <el-input placeholder="车牌号" v-model="ps_find.plateNum" clearable style="width: 120px;" />
                    </el-form-item> -->

                        <el-form-item prop="find">
                            <el-input v-model="ps_find.orderNum" clearable style="width: 250px" placeholder="行程详情/订单号">
                            </el-input>
                        </el-form-item>
                        <!-- 
                    <el-form-item prop="receiveStatus">
                        <el-select v-model="dg.ps.receiveStatus" clearable filterable placeholder="领取状态"
                            style="width: 100px">
                            <el-option v-for="(it, i) in receiveStatusArr" :key="i" :label="it.label" :value="it.value">
                            </el-option>
                        </el-select>
                    </el-form-item> -->

                        <el-form-item prop="orderStatus">
                            <el-select v-model="ps_find.statusList" multiple collapse-tags clearable filterable
                                placeholder="订单状态" style="width: 200px">
                                <el-option v-for="it in orderStates" :label="it.name" :key="it.id" :value="it.id">
                                </el-option>
                            </el-select>
                        </el-form-item>

                        <el-form-item prop="toAscDesc">
                            <el-select v-model="ps_find.orderByCondition" clearable filterable placeholder="排序"
                                style="width: 100px">
                                <el-option label="升序" value="0">
                                </el-option>
                                <el-option label="降序" value="1">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item prop="receiptStatus">
                            <el-select v-model="ps_find.receiptStatus" clearable filterable placeholder="领取状态"
                                style="width: 100px">
                                <el-option label="未领取" value="0">
                                </el-option>
                                <el-option label="已领取" value="1">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" icon="Search" @click="getDgList">
                                搜索
                            </el-button>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="success" icon="Check" @click="confirmReceive">
                                确认领取
                            </el-button>
                        </el-form-item>


                    </el-form>
                </div>
            </div>
            <el-table border @selection-change="table_list_selection_change_btn" height="60vh" ref="multipleTableRef"
                :data="mer_list" style="width: 100%">
                <el-table-column type="selection" width="35" />
                <el-table-column label="编号" width="55" fixed type="index" />
                <el-table-column width="180" property="orderNum" label="订单号" />
                <el-table-column width="120" property="plateNum" label="车牌号" />
                <el-table-column width="220" property="startTime" label="开始日期" />
                <el-table-column width="120" property="price" label="订单价格" />
                <el-table-column width="" property="details" label="行程详情" />
                <el-table-column width="120" property="status" label="订单状态">
                    <template #="{ row, column, $index }">
                        <span>
                            {{ row.status == 'NOT_GRAB' ? '未抢单' : row.status == 'READY_CAR' ? '未派车' :
                                row.status
                                    ==
                                    'CAR_READY_CONFIRME' ? '未通知' : row.status == 'DRIVER_READY_RECEIVE' ? '师傅未确认' :
                                    row.status ==
                                        'DRIVER_CONFIRMED'
                                        ? '师傅已确认' : row.status == 'START_TAKE_CUS' ? '出发去接客户' : row.status == 'ON_ROADING' ?
                                            '未完团' :
                                            row.status == 'FINISHED' ? '完成' : row.status == 'CANCELED' ? '已取消' : row.status == 'REFUSED'
                            ?
                            '已拒绝' : row.status == 'DELETE' ? '已删除' : '其他' }}
                        </span>
                    </template>
                </el-table-column>
                <el-table-column width="120" property="agentRewardMark" label="领取状态">
                    <template #="{ row, column, $index }">
                        {{ row.agentRewardMark ? '已领取' : '未领取' }}
                    </template>
                </el-table-column>
            </el-table>
        </el-dialog>
    </div>
</template>

<script setup>
import Sortable from 'sortablejs';
import { GET_TOKEN } from '@/utils/token.js'
import { ref, reactive, onMounted, computed } from 'vue'
import {
    adupPrivateSet, getPrivateSetList, recCusList, getAgentOrderList, receiptAgentReward, getTradeTypes

} from '@/api/recommend_customers.js'
import { ElMessage, ElLoading, ElMessageBox } from 'element-plus'
import { importCusCheckInData } from '@/utils/common.js'
import CircularJSON from 'circular-json'
onMounted(async () => {
    let recommend_customers = JSON.parse(localStorage.getItem('recommend_customers'))
    if (recommend_customers) {
        find_data.find = recommend_customers.find
        data_time.value = [recommend_customers.stime, recommend_customers.etime]
        find_data.stime = recommend_customers.stime
        find_data.etime = recommend_customers.etime
    }

    getPrivateSetList({
        find: '推荐客户',
        page: {
            pageNum: 1,
            pageSize: 20,
        },
    }).then(res => {
        if (res.data.list[0]) {
            table_data_list_new.value = JSON.parse(res.data.list[res.data.list.length - 1].dat)
        } else {
            console.log('no')
            table_data_list_new.value = table_data_list
        }
    })



    Sortable.create(sortableContainer.value, {
        draggable: '.drag_it',
        ghostClass: 'sortable-ghost',
        onEnd: evt => {
            const targetRow = table_data_list_new.value.splice(evt.oldIndex, 1)[0];
            table_data_list_new.value.splice(evt.newIndex, 0, targetRow);
        }
    })





    await list_api()

})
//#region 表格数据处理
const orderStates = ref([
    { id: "READY_CAR", name: "未派车" },
    // { id: "CAR_READY_CONFIRME", name: "未通知" },
    // { id: "DRIVER_READY_RECEIVE", name: "已通知" },
    // { id: "DRIVER_CONFIRMED", name: "师傅已确认" },
    // { id: "ON_ROADING", name: "已出行" },
    { id: "FINIESHED", name: "已完成" },
    // { id: "CANCELED", name: "已取消" },
    // { id: "REFUSED", name: "已拒绝" },
    // { id: "START_TAKE_CUS", name: "出发去接客户" },
    //     { id: "PENDING", name: "已待定" },
    //     { id: "GRAB_SUCCESS", name: "抢单成功" },
    //     { id: "TRANS_SUCCESS", name: "转接成功" },

])
const set_off = ref(false)
const tj = reactive({
    // 订单总价
    totalPrice: 0,
    // 可提成总金额
    agentPrice: 0,
    // 已提成总金额
    alreadyAgentPrice: 0,


})
const ps_find = reactive({
    page: {
        pageNum: 1,
        pageSize: 999,
    },
    timeType: '0',
    stime: '',
    etime: "",
    orderNum: "",
    statusList: [],
    orderByCondition: '0',
    userId: '',
    receiptStatus: '0'
})
const set_btn = (e) => {
    console.log(e)
    ps_find.userId = e.userId
    getDgList()
    set_off.value = true
}
const mer_list = ref([])
const getDgList = () => {
    getAgentOrderList(ps_find).then(res => {
        if (res.code == 1) {
            mer_list.value = res.data.list.list
            tj.totalPrice = res.data.totalPrice
            tj.agentPrice = res.data.agentMoney
            tj.alreadyAgentPrice = res.data.receiptMoney
        } else {
            return ElMessage({
                message: res.msg,
                type: 'warning',
            })
        }
    })
}
const table_list_table_list = ref([])
const table_list_selection_change_btn = (e) => {
    table_list_table_list.value = e
    console.log(table_list_table_list.value)
}
const confirmReceive = () => {
    if (table_list_table_list.value.length < 1) {
        return ElMessage({
            message: '请选择至少一条数据',
            type: 'warning',
        })
    }
    let ps = {
        ids: ''
    }
    let ids = []
    for (let i = 0; i < table_list_table_list.value.length; i++) {
        ids.push(table_list_table_list.value[i].id)
    }
    ps.ids = ids
    receiptAgentReward(ps).then(res => {
        if (res.code != 1) {
            return ElMessage({
                message: res.msg,
                type: 'warning',
            })
        } else {
            return ElMessage({
                message: res.msg,
                type: 'success',
            })
        }

    })
}
//#endregion


//#region 表格数据处理
const table_data_list = reactive([
    { label: '用车单位', field: 'companyName', width: '', off: true },
    { label: '客户名称', field: 'realName', width: '', off: true },
    { label: '客户手机号', field: 'loginPhone', width: '', off: true },
    { label: '添加时间', field: 'addTime', width: '', off: true },
    { label: '操作', field: 'set', width: '100', off: true },

])

const table_data_list_new = ref([])
const icon_off = ref(false)
// 创建排序容器的引用
const sortableContainer = ref('')

const icon_btn = () => {
    icon_off.value = !icon_off.value
    console.log(sortableContainer.value)

}
const resetTableSet = () => {
    console.log(table_data_list)
    table_data_list_new.value = JSON.parse(JSON.stringify(table_data_list))
    console.log(table_data_list)
    console.log(table_data_list_new.value)
}
const saveTableSet = () => {
    adupPrivateSet({
        dat: JSON.stringify(table_data_list_new.value),
        tbName: '推荐客户',
        tbNum: "recommend_customers",
    }).then(res => {
        if (res.code == 1) {
            return ElMessage({
                message: res.msg,
                type: 'success',
            })
        } else {
            return ElMessage({
                message: res.msg,
                type: 'warning',
            })
        }
    })
    icon_off.value = false
}

const checkbox_btn = (e, c) => {
    for (let i = 0; i < table_data_list_new.value.length; i++) {
        if (table_data_list_new.value[i].label == c.target._value) {
            table_data_list_new.value[i].off == e

        }

    }

}

const sortedItems = computed(() => {
    return [...table_data_list_new.value].sort((a, b) => a.id - b.id);
})
//#endregion



//#region 分页列表
const data_time = ref([])
const datetime_btn = (e, y, c) => {

    if (data_time.value) {
        find_data.stime = data_time.value[0]
        find_data.etime = data_time.value[1]
    } else {
        find_data.stime = ''
        find_data.etime = ''
    }

}
const data_time2 = ref([])
const datetime_btn2 = (e, y, c) => {

    if (data_time2.value) {
        ps_find.stime = data_time2.value[0]
        ps_find.etime = data_time2.value[1]
    } else {
        ps_find.stime = ''
        ps_find.etime = ''
    }

}
const list_data = ref([])
const find_data = reactive({
    page: {
        pageNum: 1,
        pageSize: 20,
    },
    find: '',
    stime: '',
    etime: "",
})
const total = ref(0)

// 分页器一夜显示多少数据页面
const size_change_btn = () => {
    find_data.page.pageNum = 1
    list_api()
}

// 分页器跳转页面
const current_change_btn = () => {
    list_api()
}

const list_api = () => {

    recCusList(find_data).then(res => {
        list_data.value = res.data.list
        total.value = res.data.total
    })
}
//#endregion

//#region 添加
const add_off = ref(false)
const title = ref('添加账户')
const add_data = reactive({
    bankName: "",
    cardName: "",
    cardNo: "",
    id: "",
})
const add_btn = () => {
    title.value = '添加账户'

    add_data.bankName = ''
    add_data.cardName = ''
    add_data.cardNo = ''
    add_data.id = ''
    add_off.value = true

}


//#endregion

//#region 表格选择
const table_list = ref([])
const selection_change_btn = (e) => {
    table_list.value = e
    console.log(e)
}
//#endregion
//#region 修改
const up_btn = () => {
    if (table_list.value.length != 1) {
        return ElMessage({
            message: '请选择一条数据！',
            type: 'warning',
        })
    }


    title.value = '修改账户'
    add_data.bankName = table_list.value[0].bankName
    add_data.cardName = table_list.value[0].cardName
    add_data.cardNo = table_list.value[0].cardNo
    add_data.id = table_list.value[0].id
    add_off.value = true
}
//#endregion

// 提交
const ok_btn = () => {

    if (!add_data.bankName) {
        return ElMessage({
            message: '请输入账户名称',
            type: 'warning',
        })
    } else if (!add_data.cardName) {
        return ElMessage({
            message: '请输入开户行',
            type: 'warning',
        })
    } else if (!add_data.cardNo) {
        return ElMessage({
            message: '请输入卡号',
            type: 'warning',
        })
    }
    if (title.value == '添加账户') {

        adupBank(add_data).then(res => {
            if (res.code == 1) {
                list_api()
                add_off.value = false
                return ElMessage({
                    message: res.msg,
                    type: 'success',
                })
            } else {
                return ElMessage({
                    message: res.msg,
                    type: 'warning',
                })
            }
        })
    } else {

        adupBank(add_data).then(res => {
            if (res.code == 1) {
                list_api()
                add_off.value = false
                return ElMessage({
                    message: res.msg,
                    type: 'success',
                })
            } else {
                return ElMessage({
                    message: res.msg,
                    type: 'warning',
                })
            }
        })
    }
}


//#region 删除
const del_btn = () => {
    if (table_list.value.length != 1) {
        return ElMessage({
            message: '请选择一条数据！',
            type: 'warning',
        })
    }

    ElMessageBox.confirm(
        `是否确认删除【${table_list.value[0].bankName}】账户?`,
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
            distinguishCancelAndClose: 'true',
        }
    )
        .then(() => {
            delBank({
                id: table_list.value[0].id
            }).then(res => {
                if (res.code == 1) {
                    list_api()
                    return ElMessage({
                        message: res.msg,
                        type: 'success',
                    })
                } else {
                    return ElMessage({
                        message: res.msg,
                        type: 'warning',
                    })
                }
            })
        })
        .catch((e) => {
            if (e == 'cancel') {
                ElMessage({
                    type: 'warning',
                    message: '取消删除成功',
                })
            }

        })

}
//#endregion

//#region 搜索
const search_btn = () => {
    localStorage.setItem('recommend_customers', CircularJSON.stringify(find_data))
    list_api()
}
//#endregion


</script>

<style scoped lang='scss'>
.filter-container {
    line-height: 30px;
    position: relative;

    .dgts-row {
        display: flex;
        line-height: 20px;
        margin-top: 5px;
        margin-bottom: 5px;
        margin-right: 30px !important;


        .dgts-text {
            line-height: 30px;
        }

        .tr-it-title {
            font-size: 15px;
        }

        .tr-it {
            font-size: 13px;
        }

        .dgts-text-tj1 {
            line-height: 30px;
            margin: 0px 10px;
            background: #fde2e2;
            border-radius: 5px;
            padding: 0px 10px;
        }

        .dgts-text-tj2 {
            line-height: 30px;
            margin: 0px 10px;
            background: #b3d8ff;
            border-radius: 5px;
            padding: 0px 10px;
        }

        /* 列表顶部工具栏统计等文本--end */

    }
}
</style>

<style>
.col-items::-webkit-scrollbar {
    width: 5px !important;
}

.col-items>label {
    margin-left: 0px !important;
    margin-top: 5px;
    width: 100%;
}


.el-table .el-table__cell {
    padding: 0px !important;
}
</style>
